package whisper.support.user.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.stereotype.Service;
import whisper.common.exception.authorization.AccountExpiredException;
import whisper.common.exception.authorization.AuthenticationException;
import whisper.common.exception.authorization.DisabledException;
import whisper.common.exception.authorization.LockedException;
import whisper.common.support.response.WebResponseCode;
import whisper.support.user.domain.User;
import whisper.support.user.repository.UserMapper;
import whisper.support.user.service.UserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by JT on 2018/5/14
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User checkUser(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        user = userMapper.findUser(user);
        if (null == user)
            throw new AuthenticationException(WebResponseCode.CODE_ERROR, WebResponseCode.MESSAGE_ERROR_USER_PASSWORD);
        if (user.getIsAvailable() == 0)
            throw new DisabledException(WebResponseCode.CODE_ERROR, WebResponseCode.MESSAGE_ERROR_USER_IS_AVAILABLE);
        if (user.getIsLock() == 0)
            throw new LockedException(WebResponseCode.CODE_ERROR, WebResponseCode.MESSAGE_ERROR_USER_IS_LOCK);
        if (user.getIsOverdue() == 0)
            throw new AccountExpiredException(WebResponseCode.CODE_ERROR, WebResponseCode.MESSAGE_ERROR_USER_IS_EXPIRED);
        return user;
    }

    @Override
    public User findByUsername(String username) {
        User user = new User();
        user.setUsername(username);
        user = userMapper.selectOne(user);
        if (null == user)
            throw new AuthenticationException(WebResponseCode.CODE_ERROR, WebResponseCode.MESSAGE_ERROR_USER_PASSWORD);
        if (user.getIsAvailable() == 0)
            throw new DisabledException(WebResponseCode.CODE_ERROR, WebResponseCode.MESSAGE_ERROR_USER_IS_AVAILABLE);
        if (user.getIsLock() == 0)
            throw new LockedException(WebResponseCode.CODE_ERROR, WebResponseCode.MESSAGE_ERROR_USER_IS_LOCK);
        if (user.getIsOverdue() == 0)
            throw new AccountExpiredException(WebResponseCode.CODE_ERROR, WebResponseCode.MESSAGE_ERROR_USER_IS_EXPIRED);
        return user;
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @Override
    public List listUsers() {
        return userMapper.selectList(new EntityWrapper<>());
    }
}
